package com.idroc.lab.testing;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import com.idroc.coelacanth.core.membership.Endpoint;
import com.idroc.coelacanth.core.membership.HeartBeatBroadcastMessage;
import com.idroc.coelacanth.core.message.Message;
import com.idroc.coelacanth.core.message.MessageDispatchHandler;
import com.idroc.coelacanth.core.message.MessageFactory;

public class MessageTestClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ChannelFactory factory = new NioClientSocketChannelFactory (
									Executors.newCachedThreadPool(),
									Executors.newCachedThreadPool());
		ClientBootstrap bootstrap = new ClientBootstrap(factory);
		
		MessageFactory fac = new MessageFactory();
		
		MessageDispatchHandler dispatcher = fac.getMessageDispatcher();
		dispatcher.addUpMessageHandler(HeartBeatBroadcastMessage.class, new MessageHandler());
	 	dispatcher.addDownMessageHandler(TestMessage.class, new MessageHandler());
		 
	 	bootstrap.setPipelineFactory(fac);
	 	 
	 	bootstrap.setOption("tcpNoDelay" , true);
	 	bootstrap.setOption("keepAlive", true); 
		ChannelFuture cf = bootstrap.connect (new InetSocketAddress("localhost", 9090));
		Channel channel = cf.getChannel();
		TestMessage tm = new TestMessage();
		tm.setMsg("hello world");
	//	channel.write(tm).awaitUninterruptibly();
		
		
		HeartBeatBroadcastMessage msg = new HeartBeatBroadcastMessage();
		Endpoint ep = new Endpoint();
		ep.setHost("127.0.0.1");
		ep.setPort(8899);
		msg.setNode(ep); 
		System.out.println(msg);
		channel.write(msg).awaitUninterruptibly();
		
		try { Thread.sleep(3000); } catch (Exception ex) {};
		
		channel.close().awaitUninterruptibly();
		factory.releaseExternalResources();
		System.out.println("==");
	}
	 
	@ChannelPipelineCoverage("all")
	static class MessageHandler extends SimpleChannelHandler {

		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
				throws Exception { 
			Message msg = (Message) e.getMessage();
			System.out.println("msg->" + msg);
			System.out.println("RemoteAddress->" + e.getRemoteAddress()); 
		}
		
	}

}
